package com.matt.components.intercepter;

import com.matt.commons.constant.CommonConstant;
import com.matt.commons.exception.BusinessException;
import com.matt.commons.model.ErrorCode;
import com.matt.commons.utils.JsonUtil;
import com.matt.commons.utils.RemoteCallUtil;
import com.matt.foundation.utils.annotation.RequiredPermissions;
import com.matt.service.remoteCall.SsoCallService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.matt.commons.constant.CommonConstant.*;

@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    SsoCallService ssoCallService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String requestUrl = request.getRequestURI();
        String params = JsonUtil.toJson(request.getParameterMap());
        log.info("system call URL:============[{}] ,params:=============[{}]", requestUrl, params);

        String ticket = request.getHeader(CommonConstant.TICKET);
        if(StringUtils.isEmpty(ticket)){
            String auth = request.getHeader(AUTH_KEY);
            String platform = request.getHeader(PLATFORM_KEY);
            String reqUUID = request.getHeader(REQ_UUID_KEY);
            String compVer = request.getHeader(COMP_VERSION_KEY);
            String url = request.getRequestURL().toString();


            if(StringUtils.isEmpty(auth) || StringUtils.isEmpty(platform) ||
                    StringUtils.isEmpty(reqUUID) || StringUtils.isEmpty(compVer) ){
                throw new BusinessException(ErrorCode.UNDEFINED, "你无权访问改系统！");
            }

            String perferSign = RemoteCallUtil.authSigh(url, compVer, reqUUID, platform);
            log.info("prefer sign " + perferSign);
            if(!perferSign.equals(auth)){
                throw new BusinessException(ErrorCode.UNDEFINED, "你无权访问改系统！！");
            }

            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        if(handlerMethod.getMethodAnnotation(RequiredPermissions.class) != null || handlerMethod.getBeanType().isAnnotationPresent(RequiredPermissions.class)){
            // 如果自己拥有NoNeedToken标注或者所属的class拥有NoNeedToken 就直接放行
            RequiredPermissions anno = handlerMethod.getMethodAnnotation(RequiredPermissions.class);

            boolean ret = ssoCallService.checkStaffPermission(ticket, anno.value());

            if (!ret){
                throw new BusinessException("23456", "没有权限");
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
